﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CMISLibrary;
using CMISLibrary.Libraries;
using BaocaoNPC.common;
using bus_TienichNPC;


namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for ChamNoNhanh.xaml
    /// </summary>
    public partial class ChamNoNhanh : UserControl
    {
        #region variable
        public String strMadviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public string strUsername = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "NPC_ATM";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        DataSet dsResult = new DataSet();
        DataSet ds_CN = new BCNPCEntities.EXCEL.ds_CN();
        DataSet ds_CAPNHAT = new BCNPCEntities.EXCEL.ds_CAPNHAT(); 
        static DataTable data;
        int thang = 0, nam = 0;
        string maloi = "";
        NPC_CHAMNO_OFFLINE_bus CHAMNO_OFFLINE_Bus = new NPC_CHAMNO_OFFLINE_bus();
        #endregion

        public ChamNoNhanh()
        {
            InitializeComponent();
            try
            {
                data = null;
                string ten_tngan = "";
                DataSet ds = new DataSet();
                ds = GlobalServices.Service_NPCUS.Ten_Tngan(strMadviqly, strUsername.ToUpper());
                ten_tngan = ds.Tables[0].Rows[0]["TEN_TNGAN"].ToString();
                GlobalServices.Service_NPCUS.select_THANGNAMCONGNO(strMadviqly, ref thang, ref nam);
                lblThangnam.Content = "Tháng năm công nợ: " + thang.ToString() + "/" + nam.ToString();
                txtThuNganVien.Text = strUsername.ToUpper() + "-" + ten_tngan;
            }
            catch (Exception ex)
            { }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private string ChuanHoaChuoi(string s)
        {
            s = s.Trim();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                sb.Append(s[i]);
                if (s[i] == ' ')
                {
                    while (s[i] == ' ')
                        i++;
                    sb.Append(s[i]);
                }
            }
            return sb.ToString();
        }

        private void copy_dataTable(DataTable dtnguon, DataTable dtDich)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    if (rgINS[i]["TIEN_NO"].ToString() == "0")
                        dr["CHECK"]= true;
                    else
                    {
                        dr["CHECK"] = false;
                    }
                    if (rgINS[i]["TTRANG_SSAI"].ToString() == "1")
                    {
                        TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLoadDL, "lblErr", "Hóa đơn: " + dsResult.Tables[0].Rows[0]["ID_HDON"].ToString() + " không được phép xử lý!");
                        return;
                    }
                    else
                    {
                        dr["TTRANG_SSAI"] = rgINS[i]["TTRANG_SSAI"];
                    }
                    //if (rgINS[i]["LAN_GIAO"].ToString() == "0")
                    //{
                    //    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLoadDL, "lblErr", "Hóa đơn: " + dsResult.Tables[0].Rows[0]["ID_HDON"].ToString() + " chưa được giao!");
                    //    return;
                    //}
                    //else
                    //{
                        dr["LAN_GIAO"] = rgINS[i]["LAN_GIAO"];
                        dr["ID_HDON"] = rgINS[i]["ID_HDON"];
                        dr["MA_KHANG"] = rgINS[i]["MA_KHANG"];
                        dr["TEN_KHANG"] = rgINS[i]["TEN_KHANG"];
                        dr["DCHI_KHANG"] = rgINS[i]["DCHI_KHANG"];
                        dr["KYTHANGNAM"] = rgINS[i]["KY"] + "-" + rgINS[i]["THANG"] + "/" + rgINS[i]["NAM"];
                        dr["TIEN_NO"] = rgINS[i]["TIEN_NO"];
                        dr["THUE_NO"] = rgINS[i]["THUE_NO"];
                        dr["TONGTIEN"] = rgINS[i]["TONGTIEN"];
                        dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"];
                        dr["STT"] = rgINS[i]["STT"];
                        dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];

                    //}
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                    dtDich.DefaultView.RowFilter = "1=1";
                }
            }
            catch (Exception ex)
            { }
        }

        private void CHECK_HOADON_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                DataRowView drv = grHdon.SelectedItem as DataRowView;
                string id = ChuanHoaChuoi(drv.Row["ID_HDON"].ToString());
                if (dsResult.Tables[0].Rows.Count == 0) return;
                if (chk.IsChecked == true)
                {
                    
                }
                else
                {
                    for (int i = dsResult.Tables[0].Rows.Count - 1; i >= 0; i--)
                    {
                        if (dsResult.Tables[0].Rows[i]["ID_HDON"].ToString() == id)
                        {
                            if (dsResult.Tables[0].Rows[i]["TIEN_NO"].ToString() == "0")
                            {
                                chk.IsChecked = true;
                                return;
                            }
                            else
                            {
                                chk.IsChecked = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void CHECK_HUY_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                DataRowView drv = grHdon.SelectedItem as DataRowView;
                string id = drv.Row["ID_HDON"].ToString();
                if (ds_CN.Tables["CHAMNO_NHANH"].Rows.Count == 0) return;
                for (int i = ds_CN.Tables["CHAMNO_NHANH"].Rows.Count - 1; i >= 0; i--)
                {
                    if (ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["ID_HDON"].ToString() == id)
                    {
                        ds_CN.Tables["CHAMNO_NHANH"].Rows[i].Delete();
                    }
                }
                ds_CN.Tables["CHAMNO_NHANH"].AcceptChanges();
                ds_CN.Tables["CHAMNO_NHANH"].DefaultView.RowFilter = "1=1";
                Cursor = Cursors.Arrow;
            }
            catch (Exception ex)
            { }
        }

        private void btnLoadDL_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string[] T_NGAN = txtThuNganVien.Text.ToString().Split('-');
                string[] id = txtId.Text.ToString().Split(',');
                DataTable data = new DataTable();
                data = null;
                for (int i = 0; i < id.Count(); i++)
                {
                    string MA = ChuanHoaChuoi(id[i].ToString());
                    if (MA == "") 
                        return;
                    long vali;
                    if (!Int64.TryParse(MA, out vali))
                    {
                        TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLoadDL, "lblErr", "ID_HDON: "+MA+" không hợp lệ!");
                        return;
                    }
                    dsResult = GlobalServices.Service_NPCUS.HDON_CHAMNONHANH(strMadviqly, T_NGAN[0].ToUpper(), Convert.ToInt64(MA));
                    //dsResult = CHAMNO_OFFLINE_Bus.HDON_CHAMNONHANH(strMadviqly, T_NGAN[0].ToUpper(), Convert.ToInt64(MA));

                    if (dsResult.Tables[0].Rows.Count == 0 || dsResult == null)
                    {
                        TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLoadDL, "lblErr", "Hóa đơn: " + id[i] + " không tồn tại hoặc đã được chấm!");
                        return;
                    }
                    DataTable dt = ds_CN.Tables["CHAMNO_NHANH"].Copy();
                    dt.DefaultView.RowFilter = "ID_HDON ='" + Convert.ToInt64(MA) + "'";
                    if (dt.DefaultView.Count == 0)
                    { copy_dataTable(dsResult.Tables[0], ds_CN.Tables["CHAMNO_NHANH"]); }
                }
                grHdon.ItemsSource = ds_CN.Tables["CHAMNO_NHANH"].DefaultView;
            }
            catch (Exception ex)
            { }
        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ds_CN.Tables["CHAMNO_NHANH"].Rows.Clear();
                data = null;
                grHdon.ItemsSource = null;
                txtId.Text = "";
            }
            catch (Exception ex)
            { }
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // check ngay
                if (dtpNgayNOP.Text == string.Empty)
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnUpdate, "lblErr", "Hãy chọn ngày cập nhật số liệu!");
                    return;
                }
                int pcount = ds_CN.Tables["CHAMNO_NHANH"].Rows.Count;
                int pcount1 = ds_CN.Tables["CHAMNO_NHANH"].Rows.Count;
                if (pcount == 0)
                { TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Không có hóa đơn nào được chọn chấm lần này"); return; }
                if (pcount1 == 0)
                { TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Không có dữ liệu chấm nợ"); return; }

                if (MessageBox.Show("Bạn có muốn cập nhật chấm nợ cho " + pcount.ToString() + " hóa đơn không?", "Thông báo", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                {
                    // nhận số liệu vào off line
                    for (int i = 0; i < ds_CN.Tables["CHAMNO_NHANH"].Rows.Count; i++)
                    {
                        //if (ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["CHECK"].ToString() == "False")
                        //{
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Clear();
                            DataRow dr = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].NewRow();
                            dr["MA_DVIQLY"] = strMadviqly;
                            dr["MA_KHANG"] = ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["MA_KHANG"].ToString();
                            dr["ID_HDON"] = Convert.ToInt64(ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["ID_HDON"]);
                            dr["TIEN_NOP"] = Convert.ToDecimal(ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["TIEN_NO"].ToString());
                            dr["THUE_NOP"] = Convert.ToDecimal(ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["THUE_NO"].ToString());
                            dr["SO_BBGIAO"] = Convert.ToInt64(ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["SO_BBGIAO"]);
                            dr["MA_TNGAN"] = strUsername.ToUpper();
                            dr["MA_TNGAN_THUHO"] = strUsername.ToUpper();
                            dr["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                            dr["NAM_HT"] = nam;
                            dr["THANG_HT"] = thang;
                            dr["TRANGTHAI"] = 0;
                            dr["GROUP_NHOM"] = "";
                            dr["NGUOI_TAO"] = strUsername;
                            dr["TINHTRANGIN"] = 0;
                            dr["NGAY_TAO"] = DateTime.Now;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Add(dr);
                            ds_CN.AcceptChanges();
                            //if (!cls.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblErr", maloi);
                                return;
                            }
                            //Ghilog
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Clear();
                            DataRow drlog = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].NewRow();
                            drlog["MA_DVIQLY"] = strMadviqly;
                            drlog["MA_KHANG"] = ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["MA_KHANG"].ToString();
                            drlog["ID_HDON"] = Convert.ToInt64(ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["ID_HDON"]);
                            drlog["SO_BBGIAO"] = Convert.ToInt64(ds_CN.Tables["CHAMNO_NHANH"].Rows[i]["SO_BBGIAO"]);
                            drlog["NAM_HT"] = nam;
                            drlog["THANG_HT"] = thang;
                            drlog["MA_TNGAN"] = strUsername.ToUpper();
                            drlog["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                            drlog["TRANGTHAI"] = 4;
                            drlog["NGUOI_TAO"] = strUsername;
                            drlog["NGAY_TAO"] = DateTime.Now;
                            drlog["GIO"] = DateTime.Now.Hour;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Add(drlog);
                            ds_CAPNHAT.AcceptChanges();
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblErr", maloi);
                                //chamno = false;
                            }
                        //}
                    }
                }
                grHdon.ItemsSource = null;
                ds_CN.Tables["CHAMNO_NHANH"].Rows.Clear();
            }
            catch (Exception ex)
            {
                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", ex.ToString());
            }
        }

        private void txtId_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    string[] T_NGAN = txtThuNganVien.Text.ToString().Split('-');
                    string[] id = txtId.Text.ToString().Split(',');
                    DataTable data = new DataTable();
                    data = null;
                    for (int i = 0; i < id.Count(); i++)
                    {
                        string MA = ChuanHoaChuoi(id[i].ToString().Trim());
                        if (MA == "")
                            return;
                        long vali;
                        if (!Int64.TryParse(MA, out vali))
                        {
                            TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLoadDL, "lblErr", "ID_HDON: " + MA + " không hợp lệ!");
                            return;
                        }
                        dsResult = GlobalServices.Service_NPCUS.HDON_CHAMNONHANH(strMadviqly, T_NGAN[0].ToUpper(), Convert.ToInt64(MA));
                        //dsResult = CHAMNO_OFFLINE_Bus.HDON_CHAMNONHANH(strMadviqly, T_NGAN[0].ToUpper(), Convert.ToInt64(MA));

                        if (dsResult.Tables[0].Rows.Count == 0 || dsResult == null)
                        {
                            TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLoadDL, "lblErr", "Hóa đơn: " + id[i] + " không tồn tại hoặc đã được chấm!");
                            return;
                        }
                        DataTable dt = ds_CN.Tables["CHAMNO_NHANH"].Copy();
                        dt.DefaultView.RowFilter = "ID_HDON ='" + Convert.ToInt64(MA) + "'";
                        if (dt.DefaultView.Count == 0)
                        { copy_dataTable(dsResult.Tables[0], ds_CN.Tables["CHAMNO_NHANH"]); }
                    }
                    grHdon.ItemsSource = ds_CN.Tables["CHAMNO_NHANH"].DefaultView;
                    txtId.Focus();
                    txtId.SelectAll();
                }
            }
            catch (Exception ex)
            { }
        }
    }
}
